import 'package:get/get.dart';

import '../../../../common/api/x_message_assemble_communicate.dart';
import '../../../../common/models/im/im_message.dart';
import '../../../../common/utils/loading.dart';
import '../../../../common/utils/o2_api_manager.dart';
import '../chat_message_tool.dart';
import 'index.dart';

class ImChatMessageListController extends GetxController {
  ImChatMessageListController();

  final state = ImChatMessageListState();
  final messageTool =  ImChatMessageTool();

   Map<String, String> headers = {};
  
  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    messageTool.init();
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final args = Get.arguments;
    if (args == null) {
      Loading.toast('args_error'.tr);
      Get.back();
      return;
    }
    if (args['messageIdList'] != null) {
      loadMessageList(args['messageIdList']);
    } else {
      Loading.toast('args_error'.tr);
      Get.back();
      return;
    }
    headers[O2ApiManager.instance.tokenName] = O2ApiManager.instance.o2User?.token ?? '';
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    messageTool.dispose();
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  Future<void> loadMessageList(List<String> messageIdList) async {
    final list = await MessageCommunicationService.to.listMessageObject(messageIdList);
    if (list != null) {
      state.msgList.addAll(list);
    }
  }

  void clickMsgItem(IMMessage msg) {
    messageTool.clickMsgItem(msg);
  }
}
